<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"  xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:replace="_header_include::frag(~{::title},~{},~{})">
    <title>后台管理系统</title>
</head>
<body>
<div id="maindiv" class="maindiv mainPadding" style="display: none;">    
    <el-breadcrumb separator="/" class="elBreadcrumb marginB20">
        <el-breadcrumb-item>Home</el-breadcrumb-item>
        <el-breadcrumb-item>数据报表</el-breadcrumb-item>
        <el-breadcrumb-item>商务来访签约区域表<span style="color:red;">（暂时支持每天更新一次数据，更新时间：每天早上7:00）</span></el-breadcrumb-item>
    </el-breadcrumb>
    <el-row class="marginB20">
        <el-button type="primary" @click="searchMonth">月统计</el-button>
        <el-button type="success" @click="searchSeason">季统计</el-button>
        <el-button type="warning" @click="searchYear">年统计</el-button> 
         <!-- <shiro:hasPermission name="statistics:trafficCallResource:export"> -->
        <el-button type="danger" @click="exportRs">导出Excel报表</el-button>   
         <!-- </shiro:hasPermission> -->
        <el-button type="primary" style="float: right;" @click="goback()">返回</el-button> 
    </el-row>
    <div class="mainSearchBg">        
        <div class="mainSearchFormBox">
           <el-form :inline="true" :model="form" class="demo-form-inline mainSearchForm" ref="form">
                <el-form-item label="统计日期：">
                    <el-date-picker format="yyyy-MM-dd" v-model="form.startTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="—" class="widthauto">
                    <el-date-picker format="yyyy-MM-dd" v-model="form.endTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="餐饮集团：">  
                    <el-select v-model="form.groupId" placeholder="全部" style="width: 100%;" clearable filterable>
                        <el-option
                            v-for="item in companyList"
                            :key="item.id"
                            :label="item.groupName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商务大区:">  
                    <el-select v-model="form.busAreaId" placeholder="全部" style="width: 100%;" clearable filterable  @change="curBusinessGroup" :disabled="isDisabled">
                        <el-option
                            v-for="item in areaList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商务组:">  
                    <el-select v-model="form.businessGroupId" placeholder="全部" style="width: 100%;" clearable filterable  @change="curBusiness" :disabled="isDisabledOrgId">
                        <el-option
                            v-for="item in orgBusinessArr"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商务经理:">  
                    <el-select v-model="form.businessManagerId" placeholder="全部" style="width: 100%;" clearable filterable :disabled="isDisabledUserId">
                        <el-option
                            v-for="item in userBusinessArr"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="区域：">  
                    <el-select v-model="form.province" placeholder="全部" style="width: 100%;" clearable filterable >
                        <el-option
                            v-for="item in provinceList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <div class="mainSearchBtnBox">
                    <el-button class="searchBtn" icon="el-icon-search" type="primary" @click="searchTable(1)" :disabled="loading">搜索</el-button>
                </div>  
            </el-form>
        </div>
        <el-row>
            <el-table 
                ref="tableData"
                tooltip-effect="dark"
                style="width: 100%"
                border
                :data="tableData"
                v-loading="loading"
                :cell-style="centerStyle"
                :header-cell-style="centerStyle"
                :span-method="arraySpanMethod">
                <el-table-column type="index" label="序号" width="55" :index="indexFun">
                    <template slot-scope="scope">
                        <span :class="{'act':scope.row.total != ''}">{{scope.$index?scope.$index:''}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="companyName" label="餐饮集团">
                    <template slot-scope="scope">
                        <span v-if="scope.row.total =='合计'" class="act">合计</span>
                        <span v-else>{{scope.row.companyName}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="businessGroupName" label="商务组">
                    <template slot-scope="scope">
                        <span :class="{'act':scope.row.total != ''}">{{scope.row.businessGroupName}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="regionName" label="区域">
                    <template slot-scope="scope">
                        <span :class="{'act':scope.row.total != ''}">{{scope.row.regionName}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="firstVisit" label="首访数">
                    <template slot-scope="scope">
                        <span :class="{'act':scope.row.total != ''}">{{scope.row.firstVisit}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="signNum" label="签约数">
                    <template slot-scope="scope">
                        <span :class="{'act':scope.row.total != ''}">{{scope.row.signNum}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="signRate" label="签约率">
                    <template slot-scope="scope">
                        <span :class="{'act':scope.row.total != ''}">{{scope.row.signRate}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="culeNum" label="净业绩金额">
                    <template slot-scope="scope">
                        <span :class="{'act':scope.row.total != ''}">{{scope.row.amount|format_number}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="sigleAmount" label="签约单笔">
                    <template slot-scope="scope">
                        <span :class="{'act':scope.row.total != ''}">{{scope.row.sigleAmount|format_number}}</span>
                    </template>
                </el-table-column>
            </el-table>
            <table-pagination :pager="pager" @change="searchTable()"></table-pagination>
        </el-row>
    </div>
</div>
<!-- import common js-->
<div th:include="_footer_include :: #jsLib"></div>
</body>
<style>
    .act{font-weight: bold;}
</style>
<script th:inline="javascript">
    var parentParam = [[${busDto}]];
    var areaList = [[${areaList}]]; // 商务大区
    var provinceList=[[${provinceList}]];// 区域
    var companyList = [[${companyList}]];
    var curDeptId=[[${areaId}]];// 当前用户所在大区
    var curOrgId = [[${busId}]]; // 当前用户所在组
    var curUserId = [[${managerId}]]; // 当前用户
    var mainDivVM = new Vue({
        el: '#maindiv',
        data: function() {
            return {
                loading: false,
                isDisabled: false,
                isDisabledOrgId: false,
                isDisabledUserId: false,
                pager:{
                    total: 0,
                    currentPage: 1,
                    pageSize: 20,
                },
                form: {
                    startTime:'',
                    endTime:'',
                    busAreaId: '',
                    businessGroupId: '',
                    businessManagerId: '',
                    province: '',
                    groupId:''
                },
                export: {
                    startTime:'',
                    endTime:'',
                    busAreaId: '',
                    businessGroupId: '',
                    businessManagerId: '',
                    province: '',
                    groupId:''
                },
                tableData: [],
                areaList: areaList,
                provinceList: provinceList,
                companyList: companyList,
                orgBusinessArr: '', // 商务组
                userBusinessArr: '', // 商务经理
            }             
        },
        filters:{
            format_number(value){
                var nStr = value;
                if('--'==nStr){
                    return nStr;
                }
                nStr += '';  
                x = nStr.split('.');  
                x1 = x[0];
                if(!x[1]){
                    x[1] = '00';
                }  
                x2 = x.length > 1 ? '.' + x[1] : '';
                var rgx = /(\d+)(\d{3})/;  
                while (rgx.test(x1)) {  
                    x1 = x1.replace(rgx, '$1' + ',' + '$2');  
                }  
                return x1 + x2;  
            },
        },
        methods: {
            centerStyle(){
                return "text-align:center"
            },
            firstCurBusiness(seleVal){ // 商务组搜索商务经理
                if(seleVal==null||seleVal==""){
                    return ;
                }
                this.getBusiness(seleVal);
            },
            curBusiness(seleVal){
                if(seleVal==null||seleVal==""){
                    return ;
                }
                this.form.businessManagerId = '';
                this.getBusiness(seleVal);
            },
            getBusiness(seleVal){
                param={};
                param.orgId=seleVal;
                param.roleCode="SWJL";
                axios.post('/base/getSaleList' ,param).then(function (response) {
                    mainDivVM.userBusinessArr=response.data.data;
                }).catch(function (error) {
                        mainDivVM.$message({
                        message: "商务经理请求失败，请稍后重试",
                        type: "error"
                    });
                });
            },
            firstCurBusinessGroup(seleVal){ // 商务大区搜索商务组
                if(seleVal==null||seleVal==""){
                    return ;
                }
                this.getBusinessGroup(seleVal);
            },
            curBusinessGroup(seleVal){
                if(seleVal==null||seleVal==""){
                    return ;
                }
                this.form.businessGroupId = '';
                this.form.businessManagerId = '';
                this.getBusinessGroup(seleVal);
            },
            getBusinessGroup(seleVal){
                param={};
                param.parentId=seleVal;
                param.orgType=2;
                axios.post('/base/getGroupList',param).then(function (response) {
                    mainDivVM.orgBusinessArr=response.data.data;
                }).catch(function (error) {
                        mainDivVM.$message({
                        message: "商务组请求失败，请稍后重试",
                        type: "error"
                    });
                });
            },
            searchTable(firstPage) {
                var startTime = this.form.startTime;
                var endTime = this.form.endTime;
                if(endTime && startTime){
                    startTime = new Date(this.form.startTime);
                    endTime = new Date(this.form.endTime);
                    if(startTime>endTime){
                        this.$message({
                            message: '开始时间不能大于结束时间',
                            type: 'warning'
                        });
                        return;
                    }
                    var date = new Date();
                    var currentDate = moment(date).format("YYYY-MM-DD");
                    var currentDateRes = new Date(currentDate);
                    if(endTime > currentDateRes){
                        this.$message({
                            message: '请选择当前日期前的时间',
                            type: 'warning'
                        });
                        return;
                    }
                    startTime = this.limitTime(startTime, null);
                    endTime = this.limitTime(null, endTime);
                }else{
                    this.$message({
                        message: '请选择起止时间',
                        type: 'warning'
                    });
                    return;
                }

                var param = {};
                param.startTime = this.minuteFormat(startTime);
                param.endTime = this.minuteFormat(endTime);
                param.pageSize = this.pager.pageSize;

                if(firstPage){
                    param.pageNum = firstPage;
                }else{
                    param.pageNum = this.pager.currentPage;
                }
                param.busAreaId = this.form.busAreaId;
                param.businessGroupId = this.form.businessGroupId;
                param.businessManagerId = this.form.businessManagerId;
                param.province = this.form.province;
                param.groupId = this.form.groupId;
                this.loading = true;
                axios.post('/busVisitSign/queryBusPage',param).then(function (response) {
                    if(!response || !response.data){
                        mainDivVM.$message({
                            message: "接口调用失败",
                            type: 'error'
                        });
                        return ;
                    }
                    var resobj= response.data;
                    if(resobj.code != '0'){
                        mainDivVM.loading = false;
                        mainDivVM.$message({
                            message: resobj.msg,
                            type: 'error'
                        });
                        return ;
                    }else if(resobj.data && resobj.data.tableData){
                        var resobjData = resobj.data;
                        var tableData = resobjData.tableData;
                        if( tableData.data.length && resobj.data.totalData ){
                            for (var i = 0; i < resobjData.totalData.length; i++) {
                                Vue.set(resobjData.totalData[i], 'total', '合计')
                            }
                            for (var j = 0; j < tableData.data.length; j++) {
                                Vue.set(tableData.data[j], 'total', '')
                            }
                            mainDivVM.summaryFun(resobjData.totalData,tableData.data)
                        }else{
                            mainDivVM.tableData = tableData.data;
                        }
                        mainDivVM.pager.currentPage = tableData.currentPage;
                        mainDivVM.pager.total = tableData.total;
                        mainDivVM.loading = false;
                        mainDivVM.export.startTime = mainDivVM.minuteFormat(startTime);
                        mainDivVM.export.endTime = mainDivVM.minuteFormat(endTime);
                        mainDivVM.export.busAreaId = mainDivVM.form.busAreaId;
                        mainDivVM.export.businessGroupId = mainDivVM.form.businessGroupId;
                        mainDivVM.export.businessManagerId = mainDivVM.form.businessManagerId;
                        mainDivVM.export.province = mainDivVM.form.province;
                        mainDivVM.export.groupId = mainDivVM.form.groupId;

                    }else{
                        mainDivVM.loading = false;
                    }
                }).catch(function (error) {
                    mainDivVM.loading = false;
                    mainDivVM.$message({
                        message: "请求失败，请稍后重试",
                        type: "error"
                    });
                });
            },
            //根据id将合计插入对应id上边
            summaryFun(totalData, tableData) {
                var resultTableData = [] // 新list
                for(var k=0;k<totalData.length;k++){
                    if(totalData[k].companyId == 99999){
                        resultTableData.push(totalData[k]);
                    }
                }
                console.log(resultTableData)
                if(curOrgId){
                    for(var n=0;n<tableData.length;n++){
                        resultTableData.push(tableData[n]);
                    }

                }else{
                    for(var i=0;i<totalData.length;i++){
                        var ind = -1;
                        for(var j=0;j<tableData.length;j++){
                            if(totalData[i].companyId === tableData[j].companyId){
                                ind = i;
                                resultTableData.push(tableData[j]);
                            }
                        }
                        if(ind != -1){
                            resultTableData.push(totalData[ind]);
                        }
                    }
                }
                mainDivVM.tableData = resultTableData;
            },
            indexFun (index) { // 表格序号
                return index;
            },
            arraySpanMethod({
                row,
                column,
                rowIndex,
                columnIndex
            }) { 
                if (rowIndex === 0) {
                    if (columnIndex === 0) {
                        return [0, 0];
                    } else if (columnIndex === 1) {
                        return [1, 3];
                    } else if (columnIndex === 2) {
                        return [0, 0];
                    }
                }
                if (row.total && row.total == '合计') {
                    if (columnIndex === 1) {
                        return [1, 2]
                    } else if (columnIndex === 2) {
                        return [0, 0]
                    }
                }
            },
            limitTime (start, end) {
                var endTime = this.minuteFormat (end);
                var startTime = this.minuteFormat (start);
                var date = new Date();
                data = this.minuteFormat (date);// 现在的时间
                data = data.slice(0,8);
                if(startTime){
                    this.form.startTime = moment(start).format("YYYY-MM-DD");
                    return this.form.startTime;
                }
                if(endTime){
                    this.form.endTime = moment(end).format("YYYY-MM-DD");
                    return this.form.endTime;      
                }
            },
            goback(){window.history.go(-1);},
            percentFormat(row, column) {//百分比格式化
                var percent = row[column.property];
                if (!percent) { // 如果没有值或值为0
                    return "0%";
                }
                percent = (percent * 1000) / 10 + "%";
                return percent;
            },
            minuteFormat (m) {
                if (!m) {return "";}
                var timeStr = new Date(m);
                var yearRes = timeStr.getFullYear()
                var monthRea = timeStr.getMonth()+1;
                monthRea = monthRea < 10 ?  "0" + monthRea : monthRea;
                var dateRes = timeStr.getDate();
                dateRes = dateRes < 10 ?  "0" + dateRes : dateRes;               
                var timeRes = "" + yearRes + monthRea + dateRes;
                return timeRes;
            },
            dateTimeFormat (dt) {
                if (!dt) {return "";}
                var d = dt.toString();
                var oYear = d.slice(0,4);
                var oMonth = d.slice(4,6);
                var oDay = d.slice(6,8);
                return oYear+"-"+oMonth+"-"+oDay;
            },
            searchSeason(){ // 季
                var today = new Date();
                var month = today.getMonth()+1;
                var startTime = '';
                switch (month) {
                    case 1 : 
                    case 2 : 
                    case 3 : startTime = today.getFullYear()+"-" + 01 + "-" + 01;break;
                    case 4 : 
                    case 5 : 
                    case 6 : startTime = today.getFullYear()+"-" + 04 + "-" + 01; break;
                    case 7 : 
                    case 8 : 
                    case 9 : startTime = today.getFullYear()+"-" + 07 + "-" + 01;break;
                    case 10 :
                    case 11 :
                    case 12 : startTime = today.getFullYear()+"-" + 10 + "-" + 01;break;
                }
               var endTime = today.getFullYear()+"-" + (today.getMonth()+1) + "-" + today.getDate();
               this.form.startTime=startTime;
               this.form.endTime=endTime;
               this.searchTable(1);
            },
            searchYear(){ // 年
               var today = new Date();
               var startTime = today.getFullYear()+"-" + 01 + "-" + 01;
               var endTime = today.getFullYear()+"-" + (today.getMonth()+1) + "-" + today.getDate();
               this.form.startTime=startTime;
               this.form.endTime=endTime;
               this.searchTable(1);
            },
            searchMonth(){ // 本月 
                var a = new Date();
                var year = a.getFullYear();
                var month = a.getMonth();
                var date = a.getDate();
                var b = new Date(year,month,date);
                var f= new Date(year,month,01);
                var c = f.valueOf();
                var startTime= new Date(c);
                this.form.startTime=startTime.getFullYear()+"-" + (startTime.getMonth()+1) + "-" + startTime.getDate();
                this.form.endTime=year+"-"+(month+1)+"-"+date;
                this.searchTable(1);
            },
            exportRs(){
                var param = {};
                param.startTime = this.export.startTime;
                param.endTime = this.export.endTime;
                param.busAreaId = this.export.busAreaId;
                param.businessGroupId = this.export.businessGroupId;
                param.businessManagerId = this.export.businessManagerId;
                param.province = this.export.province;
                param.groupId = this.export.groupId;
                axios.post('/busVisitSign/exportCompany',param,{responseType:'blob'})
                .then(function (response) {
                    var data =  response.data;
                    var fileName = response.headers.filename;
                    saveAs(data,decodeURI(fileName));
                })
                .catch(function (error) {
                    mainDivVM.$message({
                        message: "导出失败，请稍后重试",
                        type: "error"
                    });
                });
            }
        },
        created(){     
            var today = new Date();
            var startTime = moment(today).format("YYYY-MM-DD");
            var endTime = moment(today).format("YYYY-MM-DD");
            if(curDeptId){
                this.isDisabled = true;
                this.form.busAreaId = curDeptId;
                if(curOrgId){
                    this.isDisabledOrgId = true;
                    this.form.businessGroupId = curOrgId;
                    if(curUserId){
                        this.isDisabledUserId = true;
                        this.form.businessManagerId = curUserId;
                    }else{
                        this.form.businessManagerId = parentParam&&parentParam.businessManagerId ? parentParam.businessManagerId:'';
                    }
                }else{
                    this.form.businessGroupId = parentParam&&parentParam.businessGroupId ? parentParam.businessGroupId:'';
                    this.form.businessManagerId = parentParam&&parentParam.businessManagerId ? parentParam.businessManagerId:'';
                }
            }else{
                this.form.busAreaId = parentParam&&parentParam.busAreaId ? parentParam.busAreaId:'';
                this.form.businessGroupId = parentParam&&parentParam.businessGroupId ? parentParam.businessGroupId:'';
                this.form.businessManagerId = parentParam&&parentParam.businessManagerId ? parentParam.businessManagerId:'';
            }
            if(parentParam && parentParam.startTime){
                this.form.startTime = this.dateTimeFormat(parentParam.startTime);
                this.form.endTime = this.dateTimeFormat(parentParam.endTime);

                this.export.startTime = parentParam.startTime;
                this.export.endTime = parentParam.endTime;
            }else{
                this.form.startTime = startTime;
                this.form.endTime = endTime;
                this.export.startTime = this.minuteFormat(this.form.startTime);
                this.export.endTime = this.minuteFormat(this.form.endTime);
            }

            this.form.province = parentParam&&parentParam.province ? parentParam.province:'';
            this.export.province = this.form.province;
            this.export.busAreaId = this.form.busAreaId;
            this.export.businessGroupId = this.form.businessGroupId;
            this.export.businessManagerId = this.form.businessManagerId;

            var localVal=localStorage.getItem('allChangePageSize')?parseInt(localStorage.getItem('allChangePageSize')):'';
            if(localVal){this.pager.pageSize = localVal;}
            if(this.form.busAreaId){
                this.firstCurBusinessGroup(this.form.busAreaId);
            }
            if(this.form.businessGroupId){
                this.firstCurBusiness(this.form.businessGroupId);
            }
            this.searchTable();
        },
        mounted(){
            document.getElementById('maindiv').style.display = 'block';
        }
    })
    
</script>
</html>
